package com.wei.czz.framework.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wei.czz.common.dto.common.sms.SmsTemplateFlowStatDto;
import com.wei.czz.common.enums.CommonEnum;
import com.wei.czz.common.enums.ResultEnum;
import com.wei.czz.common.exception.CzzException;
import com.wei.czz.common.tool.PageDto;
import com.wei.czz.common.tool.PageQuery;
import com.wei.czz.common.vo.common.sms.SmsLogFormVo;
import com.wei.czz.framework.common.service.AesService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.wei.czz.framework.common.dao.SmsLogDao;
import com.wei.czz.framework.common.entity.SmsLogEntity;
import com.wei.czz.framework.common.service.SmsLogService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2024-06-17 21:41:13
 * className: SmsLogServiceImpl
 * version: 1.0
 * description:
 */
@Service("smsLogService")
@AllArgsConstructor
public class SmsLogServiceImpl extends ServiceImpl<SmsLogDao, SmsLogEntity> implements SmsLogService {

    private static final Logger log = LoggerFactory.getLogger(SmsLogServiceImpl.class);

    private final AesService aesService;

    @Override
    public void saveOrEdit(SmsLogEntity smsLog) {
        Long id = smsLog.getId();
        if (Objects.isNull(id)) {
            int count = baseMapper.insert(smsLog);
            log.info("插入短信发送记录完成。count={}", count);
        } else {
            int count = baseMapper.updateById(smsLog);
            log.info("修改短信发送记录完成。count={}", count);
        }
    }

    @Transactional
    @Override
    public void batchSave(List<SmsLogEntity> smsLogList) {
        boolean bool = this.saveBatch(smsLogList);
        log.info("批量保存短信发送记录完成。size={} bool={}", smsLogList.size(), bool);
    }

    @Override
    public PageDto<SmsLogEntity> getPageList(SmsLogFormVo smsLogFormVo) {
        // mp分页对象
        Page<SmsLogEntity> page = PageQuery.initPage(smsLogFormVo);

        String equalsMobile = null;
        String mobilePrefix = null;
        String mobileSuffix = null;
        if (StringUtils.isNotBlank(smsLogFormVo.getMobile())) {
            if (CommonEnum.ZERO.getValue().equals(smsLogFormVo.getMobileMatchMode())) {
                equalsMobile = aesService.encryptToHex(smsLogFormVo.getMobile());
            } else if (CommonEnum.ONE.getValue().equals(smsLogFormVo.getMobileMatchMode())) {
                mobilePrefix = smsLogFormVo.getMobile();
                if (mobilePrefix.length() != 3) {
                    log.error("手机号前缀长度不等于3");
                    throw new CzzException(ResultEnum.REQUEST_FAIL.getCode(), "请输入3位手机号前缀进行查询");
                }
            } else if (CommonEnum.TWO.getValue().equals(smsLogFormVo.getMobileMatchMode())) {
                mobileSuffix = aesService.encryptToHex(smsLogFormVo.getMobile());
            } else {
                throw new CzzException(ResultEnum.ILLEGAL_FAIL);
            }
        }

        LambdaQueryWrapper<SmsLogEntity> smsLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 匹配条件
        smsLogLambdaQueryWrapper.eq(StringUtils.isNotBlank(smsLogFormVo.getAccount()), SmsLogEntity::getAccount,
                        smsLogFormVo.getAccount())
                .eq(Objects.nonNull(equalsMobile), SmsLogEntity::getMobile, equalsMobile)
                .likeRight(Objects.nonNull(mobilePrefix), SmsLogEntity::getSubMobile, mobilePrefix)
                .eq(Objects.nonNull(mobileSuffix), SmsLogEntity::getMobileSuffix, mobilePrefix)
                .eq(Objects.nonNull(smsLogFormVo.getType()), SmsLogEntity::getType, smsLogFormVo.getType())
                .eq(Objects.nonNull(smsLogFormVo.getVersion()), SmsLogEntity::getVersion, smsLogFormVo.getVersion())
                .eq(Objects.nonNull(smsLogFormVo.getChannel()), SmsLogEntity::getChannel, smsLogFormVo.getChannel())
                .eq(Objects.nonNull(smsLogFormVo.getStatus()), SmsLogEntity::getStatus, smsLogFormVo.getStatus())
                .ge(Objects.nonNull(smsLogFormVo.getStartCreateTime()), SmsLogEntity::getCreateTime,
                        smsLogFormVo.getStartCreateTime())
                .le(Objects.nonNull(smsLogFormVo.getEndCreateTime()), SmsLogEntity::getCreateTime,
                        smsLogFormVo.getEndCreateTime());
        // 分页查询
        baseMapper.selectPage(page, smsLogLambdaQueryWrapper);
        log.info("分页查询短信发送记录完成。list.size={} totalNum={}", page.getRecords().size(), page.getTotal());
        // 封装返回
        return new PageDto<>(page);
    }

    @Override
    public List<SmsLogEntity> findList(String account, String mobile, Integer type, Integer version, Date startDate,
                                       Date endDate) {
        LambdaQueryWrapper<SmsLogEntity> smsLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        smsLogLambdaQueryWrapper.eq(StringUtils.isNotBlank(account), SmsLogEntity::getAccount, account)
                .eq(StringUtils.isNotBlank(mobile), SmsLogEntity::getMobile, mobile)
                .eq(Objects.nonNull(type), SmsLogEntity::getType, type)
                .eq(Objects.nonNull(version), SmsLogEntity::getVersion, version)
                .ge(Objects.nonNull(startDate), SmsLogEntity::getCreateTime, startDate)
                .le(Objects.nonNull(endDate), SmsLogEntity::getCreateTime, endDate)
                .eq(SmsLogEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询
        List<SmsLogEntity> smsLogList = baseMapper.selectList(smsLogLambdaQueryWrapper);
        log.info("查询短信发送记录完成。account={} mobile={} type={} version={} startDate={} endDate={} size={}",
                account, mobile, type, version, startDate, endDate, smsLogList.size());
        return smsLogList;
    }

    @Override
    public List<SmsTemplateFlowStatDto> findStatList(Integer type, Integer channel) {
        if (Objects.isNull(type)) {
            log.info("获取短信模板流水统计，传递的短信类型为空");
            return Collections.emptyList();
        }
        // 查询统计数据
        List<SmsTemplateFlowStatDto> smsTemplateFlowDtoList = baseMapper.selectStat(type, channel,
                CommonEnum.ZERO.getValue());
        log.info("查询短信模板流水统计数据完成。list.size={}", smsTemplateFlowDtoList.size());
        return smsTemplateFlowDtoList;
    }

}